package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.controller.vo.ProductAddVo;
import com.example.controller.vo.ProductUpdateVo;
import com.example.controller.vo.Result;
import com.example.entity.Interaction;
import com.example.entity.Product;
import com.example.mapper.InteractionMapper;
import com.example.mapper.ProductMapper;
import com.example.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author yzy
 * @since 2025-08-04
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InteractionMapper interactionMapper;

    @Override
    public Page<Product> pagelist(int pageNum, int pageSize, Integer isBargain, Integer categoryId, String name) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        if (StringUtils.hasText(name)) {
            ;
            queryWrapper.like("name", name);
        }
        if (isBargain != null) {
            queryWrapper.like("is_bargain", isBargain);
        }
        if (categoryId != null) {
            queryWrapper.like("category_id", categoryId);
        }
        Page<Product> productPage = productMapper.selectPage(page, queryWrapper);
        return productPage;
    }

    @Override
    public Result deleteProduct(Integer id) {
        // 检查商品是否存在
        Product product = productMapper.selectById(id);
        if (product == null) {
            return Result.failed("商品不存在");
        }
        // 执行删除操作
        int success = productMapper.deleteById(id);
        if (success == 1) {
            return Result.success("删除成功");
        } else {
            return Result.failed("删除失败，请稍后重试");
        }
    }
    @Override
    public Result userGetById(Integer id, Integer userId) {
        // 1. 查询商品详情
        Product product = productMapper.selectById(id);
        if (product == null) {
            return Result.failed("商品不存在");
        }
        // 2. 记录浏览行为（仅当用户已登录且商品状态为2时）
        if (userId != null ) {
            // 检查是否已存在相同的浏览记录
            Integer type =2;
            Interaction interaction1 = interactionMapper.selectbyidanduserid(id,userId,type) ;
            if (interaction1==null) {
                // 不存在则新增浏览记录
                Interaction interaction = new Interaction();
                interaction.setUserId(userId);
                interaction.setProductId(id);
                interaction.setType(2); // 商品状态
                interaction.setCreateTime(LocalDateTime.now()); // 浏览时间
                interactionMapper.insert(interaction);
            }else{
                //存在则更新浏览时间为当前时间
                interaction1.setCreateTime(LocalDateTime.now());
                interactionMapper.updateById(interaction1);
            }
        }
        return Result.success(product);
    }

    @Override
    public Page<Product> pageUserlist(int pageNum, int pageSize, Integer userId) {
        Page<Product> page =new Page<>(pageNum,pageSize);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
         if (userId!=null){
            queryWrapper.like("user_id",userId);
        }
        Page<Product>productPage =productMapper.selectPage(page,queryWrapper);
        return productPage;
    }

    @Override
    public Page<Product> pageUsercollect(int pageNum, int pageSize, Integer userId,Integer type) {
        Page<Product> page = new Page<>(pageNum, pageSize);

        //查询用户对应的商品ID列表（type=1：收藏 ,type=2: 浏览,type: 3 想要）
        List<Interaction> interactions = interactionMapper.selectProductIdsByUserIdAndType(userId, type);

        if (interactions == null || interactions.isEmpty()) {
            return new Page<>(pageNum, pageSize);
        }
        //遍历ID查询所有商品（优化：实际推荐用in批量查询，此处按需求保留遍历逻辑）
        List<Product> allProducts = new ArrayList<>();
        for (Interaction interaction  : interactions) {
            Integer id = interaction.getProductId();
            //用selectById直接查（更简洁）
            Product product = productMapper.selectById(id);

            if (product != null) { // 避免添加null
                allProducts.add(product);
            }
            product.setCreateTime(interaction.getCreateTime());
        }
        // 手动分页处理
        int total = allProducts.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);

        // 截取当前页数据
        List<Product> pageRecords = new ArrayList<>();
        if (startIndex < total) { // 确保起始索引有效
            pageRecords = allProducts.subList(startIndex, endIndex);
        }
        //  封装分页结果
        Page<Product> resultPage = new Page<>(pageNum, pageSize);
        resultPage.setTotal(total);
        resultPage.setRecords(pageRecords);
        return resultPage;
    }

    @Override
    public void addProduct(ProductAddVo productAddVo,Integer userId) {
        Product product = new Product();
        product.setName(productAddVo.getName());
        product.setDetail(productAddVo.getDetail());
        product.setCoverList(productAddVo.getCoverList());
        product.setOldLevel(productAddVo.getOldLevel());
        product.setCategoryId(productAddVo.getCategoryId());
        product.setInventory(productAddVo.getInventory());
        product.setPrice(productAddVo.getPrice());
        product.setIsBargain(productAddVo.getIsBargain());
        product.setUserId(userId);
        product.setCreateTime(LocalDateTime.now());
        productMapper.insert(product);
    }

    @Override
    public void updateProduct(ProductUpdateVo updateVo) {
        // 1. 校验商品是否存在
        Product existingProduct = productMapper.selectById(updateVo.getId());
        if (existingProduct == null) {
            throw new RuntimeException("商品不存在，无法修改");
        }
        // 2. 复制修改字段（保留发布者userId和创建时间，不允许修改）
        existingProduct.setName(updateVo.getName());
        existingProduct.setDetail(updateVo.getDetail());
        existingProduct.setCoverList(updateVo.getCoverList());
        existingProduct.setOldLevel(updateVo.getOldLevel());
        existingProduct.setCategoryId(updateVo.getCategoryId());
        existingProduct.setInventory(updateVo.getInventory());
        existingProduct.setPrice(updateVo.getPrice());
        existingProduct.setIsBargain(updateVo.getIsBargain());
        // 3. 执行更新
        productMapper.updateById(existingProduct);
    }


}
